package strategy

import (
	"encoding/json"
	"fmt"
	apis2 "gluenet/pkg/apis"
	"gluenet/pkg/meta"
	"net/http"
)

func GetInstanceAgentInfo(ctx *apis2.GlueContext) {
	var (
		instanceGuid string
		req          apis2.IRequest
		resp         *apis2.IResponse
	)
	if err := json.Unmarshal(ctx.RpcContext.Data.Data, &req); err != nil {
		responseFail(ctx, fmt.Errorf("unmarshall data %v", err))
		return
	}
	instanceGuid = req.Data.(string)

	var res *meta.ScheduleResults
	if err := ctx.DataBase.ScheduleResultGet(instanceGuid, &res); err != nil {
		responseFail(ctx, fmt.Errorf("get schedule result data %v", err))
		return
	}
	//res, err := orm.ScheduleResultGet(ctx, instanceGuid)
	//if err != nil {
	//	responseFail(ctx, fmt.Errorf("get schedule result data %v", err))
	//	return
	//}

	smaps, err := meta.DeCodeScheduleMaps(res.ScheduleMap)
	if err != nil {
		responseFail(ctx, fmt.Errorf("decode schedule result %v", err))
		return
	}

	mapAgents := make(map[string]*meta.Agent, len(smaps))
	for k, v := range smaps {
		var agents *meta.Agent
		if err = ctx.DataBase.AgentGet(v, &agents); err != nil {
			responseFail(ctx, fmt.Errorf("get agent error %v", err))
			return
		}
		//if len(agents) == 0 {
		//	responseFail(ctx, fmt.Errorf("agent is nil"))
		//	return
		//}
		mapAgents[k] = agents
	}

	var controlMap = map[string]interface{}{
		"guid":         res.InstancesGuid,
		"schedule_map": mapAgents,
	}

	resp = &apis2.IResponse{
		Code:    http.StatusOK,
		Message: "succeed",
		Data:    controlMap,
	}

	bts, _ := json.Marshal(resp)

	if err = ctx.RpcContext.Data.IRespond(bts); err != nil {
		ctx.Logger.Errorf("response guid %v", err)
	} else {
		ctx.Logger.Debugf("rpc get instance agent info  return %s", bts)
	}
}

func responseFail(ctx *apis2.GlueContext, err error) {
	ctx.Logger.Errorf("%v", err)
	var resp = &apis2.IResponse{
		Code:    http.StatusBadRequest,
		Message: err.Error(),
		Data:    nil,
	}
	bts, _ := json.Marshal(resp)
	ctx.RpcContext.Data.IRespond(bts)
}
